import { _decorator, Component, game, Graphics, Node, v3, Vec3 } from 'cc';
import { ModuleBase } from './ModuleBase';
import { gameConfig } from './Configs';
const { ccclass, property } = _decorator;

@ccclass('DrawLayer')
export class DrawLayer extends ModuleBase {
    private _graphics: Graphics = null;
    private _arrEndPos: Vec3[] = [];
    private _dir: Vec3 = v3();
    get graphics() {
        if (!this._graphics) {
            this._graphics = this.getComponent(Graphics);
        }
        return this._graphics;
    }

    onInit(...rest: any[]): void {

    }


    drawPath(startPos: Vec3, dir: Vec3, dt: number) {
        this._dir = dir;
        //绘制新的路径时需要将原来的路径清空
        this.clearPath();
        //将数组置为空
        this._arrEndPos = [];
        let speed = gameConfig.fireSpeed;
        let speedX = speed * this._dir.x;
        let speedY = speed * this._dir.y;
        //预测子弹的运动路径,并且将每个点进行存储
        this._arrEndPos.push(startPos);
        for (let i = 0; i < 100; i++) {
            let x = startPos.x;
            let y = startPos.y;
            speedX += gameConfig.horAcc * dt;
            speedY += gameConfig.verAcc * dt;
            x += speedX * dt;
            y += speedY * dt;
            let endPos = v3(x, y, 0);
            this._dir = v3(speedX, speedY, 0).normalize();
            this._arrEndPos.push(endPos);
            startPos = endPos;
        }
        //将预测的路径进行绘制
        for (let i = 1; i < this._arrEndPos.length; i += 2) {
            if (i + 1 >= this._arrEndPos.length) {
                break;
            }
            this.drawLine(this._arrEndPos[i], this._arrEndPos[i + 1]);
        }
    }

    drawLine(startPos: Vec3, endPos: Vec3) {
        this.graphics.moveTo(startPos.x, startPos.y);
        this.graphics.lineTo(endPos.x, endPos.y);
        this.graphics.stroke();
    }

    clearPath() {
        this.graphics.clear();
    }
}


